<template>
  <div class="app-container" ref="container">
    <!-- 下拉刷新提示 -->
    <div class="pull-refresh" :style="{ transform: `translateY(${pullRefreshHeight}px)` }">
      <div class="refresh-icon" :class="{ rotating: isRefreshing }">
        <svg viewBox="0 0 24 24" width="24" height="24">
          <path fill="currentColor" d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
        </svg>
      </div>
      <div class="refresh-text">{{ refreshText }}</div>
    </div>
    
    <div class="component-1">
      <div class="campus-bus-reservation-system-reservation">校区班车预约系统-预约</div>
      <div class="small-navigation">
        <div
          :class="['today', { selected: selectedDate === today }]"
          @click="selectDate(today)"
        >
          {{ today }}
        </div>
        <div
          :class="['today', { selected: selectedDate === tomorrow }]"
          @click="selectDate(tomorrow)"
        >
          {{ tomorrow }}
        </div>
        <div
          :class="['today', { selected: selectedDate === dayAfterTomorrow }]"
          @click="selectDate(dayAfterTomorrow)"
        >
          {{ dayAfterTomorrow }}
        </div>
      </div>
    </div>
    <div class="figma-card-container">
      <Card1 :card-data="card1Data" />
      <Card2 :card-data="card2Data" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { selectByDate } from "@/api/busmanagement/date";
import { useRouter } from "vue-router";
import { useTeacherStore } from "@/store/modules/teacher";
const teacherStore = useTeacherStore();

// 请求控制器，用于取消请求
let abortController = null;

// 下拉刷新相关变量
const container = ref(null);
const pullRefreshHeight = ref(0);
const isRefreshing = ref(false);
const refreshText = ref("下拉刷新");
const startY = ref(0);
const currentY = ref(0);
const pulling = ref(false);
const maxPullHeight = 80; // 最大下拉高度
const triggerHeight = 50; // 触发刷新的高度

// 下拉刷新相关方法
const handleTouchStart = (e) => {
  if (container.value.scrollTop === 0) {
    startY.value = e.touches[0].clientY;
    pulling.value = true;
  }
};

const handleTouchMove = (e) => {
  if (!pulling.value) return;
  
  currentY.value = e.touches[0].clientY;
  const distance = currentY.value - startY.value;
  
  // 只允许向下拉动
  if (distance > 0) {
    e.preventDefault();
    
    // 计算拉动高度，使用缓动效果
    const height = Math.min(distance * 0.5, maxPullHeight);
    pullRefreshHeight.value = height;
    
    // 更新提示文字
    if (height >= triggerHeight) {
      refreshText.value = "释放立即刷新";
    } else {
      refreshText.value = "下拉刷新";
    }
  }
};

const handleTouchEnd = () => {
  if (!pulling.value) return;
  
  pulling.value = false;
  
  // 如果拉动高度超过触发高度，执行刷新
  if (pullRefreshHeight.value >= triggerHeight) {
    isRefreshing.value = true;
    refreshText.value = "正在刷新...";
    
    // 使用location.reload()刷新页面
    setTimeout(() => {
      location.reload();
    }, 500);
  } else {
    // 否则回弹
    pullRefreshHeight.value = 0;
  }
};

// 监听触摸事件
onMounted(() => {
  teacherStore.fetchTeacherInfo().then(() => {
    // 如果教师信息为空，则跳转到 Myinfo 界面
    if (!teacherStore.teacherInfo || Object.keys(teacherStore.teacherInfo).length === 0) {
      // 使用 Vue Router 跳转，假设已导入 router
      // 若未在 <script setup> 中导入，请在顶部添加：import { useRouter } from 'vue-router';

      router.push("/campusBus/Myinfo"); // 确保路由名称正确
    }else{
      getList();
    }
  });
  
  // 添加触摸事件监听
  if (container.value) {
    container.value.addEventListener('touchstart', handleTouchStart, { passive: false });
    container.value.addEventListener('touchmove', handleTouchMove, { passive: false });
    container.value.addEventListener('touchend', handleTouchEnd, { passive: false });
  }
});

// 移除触摸事件监听和清理请求控制器
onUnmounted(() => {
  if (container.value) {
    container.value.removeEventListener('touchstart', handleTouchStart);
    container.value.removeEventListener('touchmove', handleTouchMove);
    container.value.removeEventListener('touchend', handleTouchEnd);
  }
  
  // 组件卸载时取消请求
  if (abortController) {
    abortController.abort();
    abortController = null;
  }
});

const getFormattedDate = (date) => {
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${month}.${day}`;
};

// 获取今天的日期
const todayDate = new Date();
const today = ref(getFormattedDate(todayDate));

// 获取明天的日期
const tomorrowDate = new Date();
tomorrowDate.setDate(todayDate.getDate() + 1);
const tomorrow = ref(getFormattedDate(tomorrowDate));

// 获取后天的日期
const dayAfterTomorrowDate = new Date();
dayAfterTomorrowDate.setDate(todayDate.getDate() + 2);
const dayAfterTomorrow = ref(getFormattedDate(dayAfterTomorrowDate));

// 定义当前选中的日期，默认为今天
const selectedDate = ref(today.value);

// 防抖函数
function debounce(fn, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 选中日期的方法
const selectDate = (date) => {
  selectedDate.value = date;
  // 确保教师信息已加载
  if (teacherStore.teacherInfo && teacherStore.teacherInfo.teacherCode) {
    debouncedGetList(); // 使用防抖后的函数
  }
};

// 创建防抖后的getList函数，延迟300ms执行
const debouncedGetList = debounce(getList, 300);

// 获取格式化日期字符串的函数，用于API调用，格式为 YYYY-MM-DD
const formatDateForApi = (dateString) => {
  const currentYear = new Date().getFullYear(); // 获取当前年份
  const [month, day] = dateString.split("."); // 分割月份和日期
  return `${currentYear}-${month}-${day}`; // 拼接成 YYYY-MM-DD 格式
};

// 引入 FigmaCard 组件
import Card1 from "./Card1.vue";
import Card2 from "./Card2.vue";

const loading = ref(true); // 加载状态
const list = ref([]); // 列表数据
const card1Data = ref([]); // 存储line为1或2的数据
const card2Data = ref([]); // 存储其他line的数据

/** 查询列表 */
async function getList() {
  // 取消之前的请求（如果存在）
  if (abortController) {
    abortController.abort();
  }
  
  // 创建新的请求控制器
  abortController = new AbortController();

  loading.value = true; // 设置加载状态为 true
  card1Data.value = []; // 清空 Card1 数据
  card2Data.value = []; // 清空 Card2 数据
  
  try {
    const formattedDate = formatDateForApi(selectedDate.value); // 格式化选中的日期
    // 传递 signal 给 API 调用
    const res = await selectByDate(formattedDate, { signal: abortController.signal }); // 调用 API 获取数据
    //过滤掉status为2和3的预约
    list.value = res.data.filter((item) => item.status !== 2 && item.status !== 3); // 更新列表数据

    // 根据 line 字段过滤数据
    list.value.forEach((item) => {
      if (
        item.tBusSchedule &&
        (item.tBusSchedule.line === 1 || item.tBusSchedule.line === 2)
      ) {
        card1Data.value.push(item);
      } else {
        card2Data.value.push(item);
      }
    });
  } catch (error) {
    // 忽略取消请求的错误
    if (error.name !== 'AbortError') {
      console.error("获取班车预约列表失败:", error); // 打印错误信息
      list.value = []; // 清空列表数据
      card1Data.value = []; // 清空 Card1 数据
      card2Data.value = []; // 清空 Card2 数据
    }
  } finally {
    loading.value = false; // 无论成功或失败，都设置加载状态为 false
  }
}
const router = useRouter();

// 页面加载时获取初始列表数据
defineOptions({
  name: "ReservationComponent",
});
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  justify-content: flex-start;
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 下拉刷新样式 */
.pull-refresh {
  position: absolute;
  top: -60px;
  left: 0;
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  transition: transform 0.3s ease;
  z-index: 10;
}

.refresh-icon {
  margin-bottom: 5px;
  color: #3b99fb;
}

.refresh-icon.rotating svg {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.refresh-text {
  font-size: 14px;
  color: #666;
}

.component-1 {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 120px;
  border-radius: 6px; /* 从小导航的borderRadius推断，整个组件可能也有圆角 */
}

.campus-bus-reservation-system-reservation {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 70px;
  font-size: 20px;
  line-height: 1.2102272727272727em;
  color: #ffffff; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}

.small-navigation {
  top: 20px;
  width: 306px;
  height: 28px;
  border-radius: 6px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around; /* 调整子元素的布局 */
}

.rectangle-3 {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 108px;
  height: 28px;
  background-color: #ffffff; /* 假设背景色为白色，Figma数据中未明确给出 */
  border-radius: 6px;
  /* 这是一个背景矩形，用于高亮"今天" */
}

.today {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 90px;
  height: 22px;
  font-weight: 400;
  font-size: 18px;
  line-height: 1.2102272245619032em;
  text-align: left;
  color: #3b99fb;
  background-color: #ffffff;
  border-radius: 6px;
}

.today.selected {
  background-color: #3b99fb;
  color: #ffffff;
}

.date-11-08 {
  position: absolute;
  left: 148px;
  top: 3px;
  width: 43px;
  height: 22px;
  font-family: "Inter";
  font-weight: 400;
  font-size: 18px;
  line-height: 1.2102272245619032em;
  text-align: left;
  color: #000000; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}
.date-11-09 {
  position: absolute;
  left: 263px;
  top: 3px;
  width: 43px;
  height: 22px;
  font-family: "Inter";
  font-weight: 400;
  font-size: 18px;
  line-height: 1.2102272245619032em;
  text-align: left;
  color: #000000; /* 假设文本颜色为黑色，Figma数据中未明确给出 */
}
/* FigmaCard组件容器样式：设置上外边距避免与component-1重叠 */
.figma-card-container {
  /* height: auto; */
  display: flex;
  flex-direction: column;
}
</style>
